<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" label-width="80px" :inline="true" class="hear-ss">
      <el-form-item label="提交人">
        <el-input v-model="queryParams.createByName" placeholder="请输入提交人" clearable></el-input>
      </el-form-item>
      <el-form-item label="登记时间">
        <el-date-picker
          :disabled="isView"
          v-model="queryParams.hyshDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="卫生情况">
        <el-select v-model="queryParams.hyshFlag" clearable placeholder="请选择">
          <el-option
            v-for="item in hygieneOptions"
            :label="item.dictLabel"
            :value="item.dictValue"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" icon="el-icon-search" size="small">搜索</el-button>
        <el-button @click="reset" icon="el-icon-refresh" size="small">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 添加按钮 -->
    <div style="margin: 20px 0px 8px 0px"></div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd" icon="el-icon-plus" size="small">新增宿舍卫生信息</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['violative:apply:process']">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          @click="batchDelete"
          :disabled="multiple"
        >删除
        </el-button>
      </el-col>
    </el-row>
    <!-- 表单 -->
    <el-table v-loading="loading" :data="form" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="buildName" label="楼栋名称" align="center"></el-table-column>
      <el-table-column prop="dormName" label="宿舍名称" align="center"></el-table-column>

      <el-table-column prop="hydoDate" label="登记时间" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.hydoDate!= null">{{ parseTime(scope.row.hydoDate ) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="hydoFlag" label="卫生情况" align="center">
        <template slot-scope="scope">{{getDictLabel(hygieneOptions,scope.row.hydoFlag)}}</template>
      </el-table-column>
      <el-table-column prop="hydoDesc" label="卫生情况描述" align="center"></el-table-column>
      <el-table-column prop="createByName" label="提交人" align="center"></el-table-column>
      <el-table-column prop="createTime" label="提交时间" :show-overflow-tooltip="true" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.createTime!= null">{{ parseTime(scope.row.createTime ) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-tooltip content="修改违纪" placement="top">
            <el-button
              size="mini"
              type="success"
              icon="el-icon-edit"
              circle
              @click="handleEdit(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              size="mini"
              icon="el-icon-delete"
              type="danger"
              circle
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div>
      <el-pagination
        class="page"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 40, 60]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 添加违纪弹框 -->
    <el-dialog
      title="编辑宿舍卫生信息"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="cancelRule"
    >
      <el-form :model="form1" :rules="rules" ref="form1" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="楼栋" prop="buidId">
<!--         options:[{children:[{children:[{}] }] }]     -->
              <el-cascader
                v-model="form1.buidId"
                :props="props_builds"
                >
              </el-cascader>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="楼栋" prop="buidId">
              <el-select
                v-model="form1.buidId"
                clearable
                placeholder="请选择"
                style="width:100%"
                @change="getDormitoryList"
              >
                <el-option
                  v-for="item in buildList"
                  :label="item.locationName"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼栋" prop="buidId">
              <el-select v-model="form1.dormId" clearable placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in dormitoryList"
                  :label="item.locationName"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="卫生情况" prop="hydoFlag">
              <el-select v-model="form1.hydoFlag" clearable placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in hygieneOptions"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登记时间" prop="hydoDate">
              <el-date-picker
                style="width:100%"
                :disabled="isView"
                v-model="form1.hydoDate"
                type="datetime"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="情况描述" prop="hyshDesc">
          <el-input v-model="form1.hydoDesc" style="width:100%" clearable></el-input>
        </el-form-item>
        <el-form-item label="图片:" prop="fileList">
          <el-upload
            v-if="!isView"
            :action="upload.url"
            list-type="picture-card"
            :headers="headers"
            :on-success="onSuccess"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :file-list="fileList"
            multiple
            :limit="3"
            :before-upload="onBeforeImgUpload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div v-else>
            <el-image
              v-for="item in fileList"
              style="width: 100px; height: 100px;margin-right: 10px;"
              :key="item.url"
              :src="item.url"
              :preview-src-list="[item.url]"
            ></el-image>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="!isView">
        <el-button @click="cancelRule">取 消</el-button>
        <el-button type="primary" @click="addRule()" :loading="editLoading">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  // 例如：import 《组件名称》 from '《组件路径》';
  import {getToken} from "@/utils/auth";
  import {
    getList,
    addOrUpdateHygiene,
    deleteByIds,
    buildList,
    getlistbuild
  } from "@/api/workmgr/dormitoryHygiene";

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      buildPid:'',
      pid: '',
      props_builds:{
        lazy: true,
        lazyLoad(node, resolve) {
          const {level} = node;
          let pid = node.value ? node.value : 0;
          let type = 0;
          if (level == 0) {
            type = 1;
          }
          if (level == 1) {
            type = 2;
          }
          if (level == 2) {
            type = 6;
          }
          buildList({locationType: type, locationPid: pid, level: level}).then(resp => {
            const buildList = resp.data;
            const nodes = []
            for (let i = 0; i < buildList.length; i++) {
              let node = {}
              node.value = buildList[i].id
              node.label = buildList[i].locationName
              nodes.push(node)
            }

            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes);
          });

        }
      },
      upload: {
        url: process.env.VUE_APP_BASE_API + "/test/uploadImage",
        showUrl: process.env.VUE_APP_BASE_API + "/school/file/"
      },
      dialogApprovalVisible: false,
      multiple: true,
      isView: false,
      //审批记录
      activities: [],
      // 遮罩层
      loading: false,
      editLoading: false,
      //弹框
      dialogVisible: false,
      dialogVisible1: false,
      // 分页总页数
      total: 0,
      //查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 状态数据字典
      statusOptions: [],
      gradeOptions: [],
      //添加违规参数
      form1: {
        dormId: null,
        buidId: null,
        hyshFlag: null,
        hyshDate: null,
        hyshDesc: null
      },
      form2: {},
      data: {
        applyDesc: "",
        applyID: "",
        applyTitle: "",
        approvedBy: "",
        attachment: "",
        businessKey: "",
        currNode: "",
        flag: 0,
        lastNode: "",
        processInstanceId: "",
        taskId: "",
        variables: {}
      },
      //多选绑定数组
      violative: [],
      //表单绑定对象
      form: [],
      //表单验证
      rules: {
        buidId: [{ required: true, message: "请选择楼栋", trigger: "blur" }],
        dormId: [{ required: true, message: "请选择宿舍", trigger: "blur" }],
        hydoDate: [
          { required: true, message: "请输入登记时间", trigger: "blur" }
        ],
        hydoFlag: [
          { required: true, message: "请选择卫生情况", trigger: "blur" }
        ]
      },
      //文件上传数组
      fileList: [],
      hygieneOptions: [],
      rowList: [],
      buildList: [],
      dormitoryList: []
    };
  },
  // 监听属性 类似于data概念
  computed: {
    headers() {
      return {
        Authorization: getToken()
      };
    }
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
/*    getBuild(){
      getlistbuild().then(resp => {
        const building = resp.data;
      });
    },*/
    onBeforeImgUpload(file) {
      // 判断是否符合文件大小的限制需求
      const isLt2M = file.size / 1024 / 1024 < 2
      // 判断是否符合文件类型需求
      if (!isLt2M) {
        this.$message({
          message: `上传文件大小不能超过2M!`,
          type: 'warning'
        })
      }
      return isLt2M
    },
/*    getDormitoryList(val) {
      this.form1.dormId = null;
      buildList({ locationType: 6, locationPid: val }).then(resp => {
        this.dormitoryList = resp.data;
      });
    },
    getBuildList() {
      buildList({ locationType: 1, locationPid: 0 }).then(resp => {
        this.buildList = resp.data;
      });
    },*/

    getDictLabel(list, value) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].dictValue == value) {
          return list[i].dictLabel;
        }
      }
    },
    handleSelectionChange(selection) {
      console.log(selection);
      this.rowList = selection;
      this.multiple = !selection.length;
    },
    //违纪查询
    getList() {
      this.loading = true;
      getList(this.queryParams).then(res => {
        this.form = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    //搜索按钮操作
    search() {
      this.getList();
    },
    //重置按钮操作
    reset() {
      this.fileList = undefined;
      this.queryParams.createByName = null;
      this.queryParams.hyshDate = null;
      this.queryParams.hyshFlag = null;
      this.resetForm("queryForm");
      this.search();
    },
    //添加违纪取消按钮
    cancelRule() {
      this.violative = [];
      this.fileList = [];
      this.resetForm("queryForm1");
      this.dialogVisible = false;
    },
    //添加违纪打开按钮
    handleAdd() {
      this.dialogVisible = true;
      this.isView = false;
      this.violative = [];
      this.fileList = [];
      (this.form1 = {
        dormId: null,
        buidId: null,
        hyshFlag: null,
        hyshDate: null,
        hyshDesc: null
      }),
        this.resetForm("form1");
    },
    //添加违纪提交按钮
    addRule() {
      this.$refs.form1.validate(valid => {
        debugger
        const formbuidId = this.form1.buidId;
        this.form1.buidId = formbuidId[0];
        this.form1.dormId = formbuidId[1];
        if (valid) {
          let filePath = [];
          for (let i = 0; i < this.fileList.length; i++) {
            filePath.push(this.fileList[i].dataUrl);
          }
          this.form1.hydoImage1 = filePath.join(",");
          this.editLoading = true;
          addOrUpdateHygiene(this.form1).then(res => {
            this.$message({ message: "提交成功", type: "success" });
            this.dialogVisible = false;
            this.editLoading = false;
            this.getList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //上传
    handleRemove(file, fileList) {
      this.fileList = fileList;
      console.log("remove", fileList);
    },
    handlePreview(file) {
      console.log(file, 231213);
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多能上传 3 个文件文件");
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    onSuccess(response, file, fileList) {
      this.getFileList(fileList);
      console.log("onSuccess", fileList);
    },
    getFileList(allFileList) {
      if (!allFileList) {
        return;
      }
      for (let i = 0; i < allFileList.length; i++) {
        if (allFileList[i].response) {
          this.fileList.push({
            name: allFileList[i].name,
            url: this.upload.showUrl + allFileList[i].response.result,
            dataUrl: allFileList[i].response.result
          });
        }
      }
    },
    handleEdit(row) {
      this.dialogVisible = true;

      this.form1 = JSON.parse(JSON.stringify(row));
      if (this.form1.hydoImage1) {
        this.fileList = [];
        const files = this.form1.hydoImage1.split(",");
        for (let i = 0; i < files.length; i++) {
          this.fileList.push({
            name: files[i],
            url: this.upload.showUrl + files[i],
            dataUrl: files[i]
          });
        }
      }
    },
    handleDelete(row) {
      this.$confirm("确认要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteByIds([row.id]).then(resp => {
          this.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    batchDelete() {
      const row = this.rowList;
      let ids = [];
      for (let i = 0; i < row.length; i++) {
        ids[i] = row[i].id;
      }
      this.$confirm("确认要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteByIds(ids).then(resp => {
          this.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    handledApproval() {
      this.rowList;
      let ids = [];
      let names = [];
      for (let i = 0; i < this.rowList.length; i++) {
        ids[i] = this.rowList[i].id;
        names[i] = this.rowList[i].violativeName;
      }
      this.approvalForm.ids = ids.join(",");
      this.weijiName = names.join(",");
      this.approvalForm.noticeType = "2";
      this.dialogApprovalVisible = true;
    },

    //分页
    handleSizeChange(num) {
      this.queryParams.pageSize = num;
      this.getList();
    },
    handleCurrentChange(num) {
      this.queryParams.pageNum = num;
      this.getList();
    },

    handleClose() {
      this.dialogVisible1 = false;
      this.dialogVisible2 = false;
    },
    //预览图片
    handlePreview1(val) {
      console.log(val, 585);
      if (val) {
        const image = new Image();
        image.src = process.env.VUE_APP_BASE_API + "/school/file/" + val.url;
        const imgWindow = window.open(val);
        imgWindow.document.write(image.outerHTML);
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getList();
    this.getBuildList();
    this.getDicts("hydo_flag").then(response => {
      this.hygieneOptions = response.data;
    });
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getBuild();
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {} // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
  <style lang='scss' scoped>
.page {
  float: right;
  margin: 10px 0px 0px 150px;
  padding-right: 80px;
}
</style>
